package com.lovo.order.service;

import com.lovo.order.dao.ITicketDao;
import com.lovo.order.dao.ITicketIndexDao;
import com.lovo.order.entity.TicketEntity;
import com.lovo.order.entity.TicketEntity_Index;
import com.lovo.util.ConvertBeanUtil;
import com.lovo.util.SysUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class TicketService {
  @Autowired
 RedisTemplate<String,Object> redisTemplate;
  @Autowired
  ITicketDao ticketDao;
  @Autowired
  private ITicketIndexDao ticketIndexDao;
    int i=0;
  //  @Scheduled(fixedDelay = 2000)
    public void  test(){
        System.out.println("执行"+i);
        i++;
    }
    @Scheduled(fixedDelay = 1000)
    public void  ticket(){
        while (redisTemplate.hasKey(SysUtil.MOVIE_KEY)){
            LinkedHashMap maps= (LinkedHashMap) redisTemplate.opsForList().leftPop(SysUtil.MOVIE_KEY);
            TicketEntity t=new TicketEntity();
            t.setInfo(String.valueOf(maps.get("info")));
            t.setMovieDate(String.valueOf(maps.get("movieDate")));
            t.setMovieName(String.valueOf(maps.get("movieName")));
            t.setPrice(Float.parseFloat(String.valueOf(maps.get("price"))));
            t.setNum(Integer.parseInt(String.valueOf(maps.get("num"))));
            t.setMovieNumber(String.valueOf(maps.get("movieNumber")));
            t.setSellNum(0);
           t= ticketDao.save(t);

           //放入提示消息队列
            redisTemplate.opsForList().rightPush(SysUtil.NOTIFY_KEY_S,1);
            //获得一次电影数据，记录电影数据的拉取次数
            if(redisTemplate.hasKey(SysUtil.NOTIFY_KEY_NUM)){
                 Double num=  redisTemplate.opsForZSet()
                           .incrementScore(SysUtil.NOTIFY_KEY_NUM,"movie",1);
                   redisTemplate.opsForValue().set(SysUtil.NOTIFY_KEY_NUM_SUM,num);
            }else {
                //不存在
                redisTemplate.opsForZSet()
                        .add(SysUtil.NOTIFY_KEY_NUM,"movie",1);
                redisTemplate.opsForValue().set(SysUtil.NOTIFY_KEY_NUM_SUM,1);


            }

////            //保存到ES数据库
//            TicketEntity_Index ticketEntity_index=null;
//            ticketEntity_index=   ConvertBeanUtil.copy(t,TicketEntity_Index.class);
//            ticketIndexDao.save(ticketEntity_index);
        }

    }
}
